import {Button, Divider, message, Modal, Popconfirm, Space, Switch, Table, Tag} from "antd";
import Search from "antd/es/input/Search";
import React, {useEffect, useState} from "react";
import {ColumnsType} from "antd/es/table";
import {userDelete, userPage, userResetPassword} from "@/api/user";
import {UserAuthDrawer, UserEditDrawer, UserInfoDrawer} from "@/pages/authority/components";
import {
    changeUserDrawer,
    defaultUserDrawerProp,
    DrawerType,
    UserDrawerProp,
    UserListProp,
    UserQueryProp
} from "@/pages/authority/modules";
import {color} from "@/utils/color";
import {AuthButton} from "@/components";
import {ExclamationCircleFilled} from "@ant-design/icons";

const AuthorityUserPage = () => {

    const columns: ColumnsType<UserListProp> = [
        {
            title: '序号',
            key: 'index',
            dataIndex: 'index',
            align: 'center',
            width: 50,
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '用户名称',
            key: 'name',
            dataIndex: 'name',
            align: 'center',
        },
        {
            title: '手机号',
            key: 'phone',
            dataIndex: 'phone',
            align: 'center',
        },
        {
            title: '邮箱',
            key: 'email',
            dataIndex: 'email',
            align: 'center',
        },
        {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            align: 'center',
            render: (text, record, index) => <Switch checkedChildren="正常" unCheckedChildren="禁用" checked={record.status === 1} />
        },
        {
            title: '角色',
            key: 'userRole',
            dataIndex: 'userRole',
            align: 'center',
            render: (text, record) => <Space>
                {record.userRole && record.userRole.map((item, index) => <Tag color={color(index + 1)} key={item.roleId}>{item.roleName}</Tag>)}
            </Space>
        },
        {
            title: '操作',
            key: 'active',
            align: 'center',
            width: 300,
            render: (text, record, index) => (
                <Space size={'small'}>
                    <AuthButton code="authority.user.edit" type="primary" size="small" onClick={() => openDrawer(record.id, 'edit')} title="编辑"/>
                    <AuthButton code="authority.user.info" type="primary" size="small" onClick={() => openDrawer(record.id, 'info')} title="详情"/>
                    <AuthButton code="authority.user.reset" type="primary" size="small" onClick={() => resetPassword(record.id)} title="重置密码"/>
                    <AuthButton code="authority.user.delete" type="primary" size="small" danger onClick={() => deleteUserHandler(record.id)} title="删除"/>
                </Space>
            ),
        },
    ]

    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [datasource, setDatasource] = useState<UserListProp[]>([]);
    const [query, setQuery] = useState<UserQueryProp>({page: 1, size: 10});
    const [loading, setLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [userDrawer, setUserDrawer] = useState<UserDrawerProp>({...defaultUserDrawerProp});


    const openDrawer = (userId: number, types: DrawerType) => setUserDrawer(changeUserDrawer(types, userId, true))

    const closeDrawer = (types: DrawerType, isLoad = false) => {
        setUserDrawer(defaultUserDrawerProp);
        if (isLoad) {
            loadData(query)
        }
    };

    const deleteUserHandler = async (id?: number) => {
        Modal.confirm({
            title: '警告',
            icon: <ExclamationCircleFilled />,
            content: '确认删除当前用户？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                await userDelete(id ? id.toString() : selectedRowKeys.toString());
                await loadData(query)
                message.success('删除成功')
            },
            onCancel: () => {}
        });



    }

    const resetPassword = async (id: number) => {
        const result = await userResetPassword(id);
        message.success('密码重置成功，新密码已经发送到邮箱！')
    }

    const loadData = async (data: UserQueryProp) => {
        const {total, records} = await userPage(data);
        setQuery(data);
        setDatasource(records);
        setTotal(total);
    }

    const rowSelection = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: UserListProp[]) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
    };

    useEffect(() => {
        loadData(query)
    }, [])



    return <>
        <Space>
            <AuthButton title='刷新' code='authority.user.refresh' type="primary" onClick={() => loadData(query)} />
            {/*<Button type="primary" onClick={() => loadData(query)}>刷新</Button>*/}
            <Button type="primary">禁用</Button>
            <Button type="primary">解禁</Button>
            <AuthButton title='删除' code='authority.user.batch.delete' type="primary" danger disabled={selectedRowKeys.length <= 0} onClick={() => deleteUserHandler()} />
            <Divider type="vertical" />
            <Search placeholder="请输入用户名称" enterButton="搜索" />
        </Space>
        <Table
            bordered
            size={'small'}
            columns={columns}
            dataSource={datasource}
            style={{ marginTop: 10 }}
            rowKey={(record) => record.id}
            pagination={{
                onShowSizeChange: (current, size) => loadData({...query, page: current, size: size}),
                onChange: (page, pageSize) => loadData({...query, page: page, size: pageSize}),
                showTotal: () => `共 ${total} 个`,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSize: query.size,
                current: query.page,
                size: 'default',
                total: total,
            }}
            rowSelection={{
                type: 'checkbox',
                selectedRowKeys: selectedRowKeys,
                onChange: (selectedRowKeys: React.Key[], selectedRows: UserListProp[]) => {
                    setSelectedRowKeys([...selectedRowKeys.map(item => item as number)])
                }
            }}
            loading={loading}
        />
        <UserEditDrawer
            visible={userDrawer.editVisible}
            userId={userDrawer.userId}
            close={(isLoad) => closeDrawer('edit', isLoad)}
        />
        <UserInfoDrawer
            visible={userDrawer.infoVisible}
            userId={userDrawer.userId}
            close={() => closeDrawer('info')}
        />
        <UserAuthDrawer
            visible={userDrawer.authVisible}
            userId={userDrawer.userId}
            close={() => closeDrawer('auth')}
        />
    </>
}

export default AuthorityUserPage;